package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import conversion.ObjectToString;
import dataobjects.Message;

/**
 * Servlet implementation class GetMessages
 */
public class GetMessages extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetMessages() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		response.setContentType("text/xml");
		Context ctx;
		try {
			ctx = new InitialContext();
		
			List messageList = new ArrayList();
	      if(ctx != null ){
	    	  DataSource ds = 
	  	            (DataSource)ctx.lookup(
	  	               "java:comp/env/jdbc/AndroidDB");  
	    	 Connection c =  ds.getConnection();
	    	 Statement stmt = c.createStatement();
			ResultSet set = stmt.executeQuery("select id, categoryID, message from suggestions");
	    	 if(  set.first() ){ //There is something valid returning
	    		 do{
	    			 long id = set.getLong("id");
	    			 long categoryID = set.getLong("categoryID");
	    			 String messageText = set.getString("message");
	    			 
	    			 Message message = new Message();
	    			 message.setId( id );
	    			 message.setCategoryID(categoryID);
	    			 message.setMessage(messageText);
	    			 messageList.add( message); 
	    			 
	    		 }while(set.next());
	    		 
	    	 }
	    	 set.close();
	    	 stmt.close();
	    	 c.close();
	    	 
	    	 out.println( new ObjectToString().convert( messageList )) ;
	    	 
	    	 
	    	  
	      }
	         

	      
		} catch (Exception e) {
			// TODO Auto-generated catch block
			out.println(e.getMessage());
		}
		
		
       
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
